const {
    read_plain,
    get_fst_file,
    get_full_path,
    format_bytes,
} = require("../utils/file_tool");
const { BaseCommand } = require("./base");
const fs = require("node:fs");
const il = require("iconv-lite");
const path = require("node:path");
const display_tool = require("../utils/display_tool");

class UnzipCommand extends BaseCommand {
    async execute() {
        const src = get_fst_file(this.selfData.src);
        const dst = get_full_path(this.selfData.dst, "FOLDER");
        const encoding = this.selfData?.options?.encoding;
        const _totalSize = fs.statSync(src).size;
        const _unzippedSize = 0;
        const _uncompressedSize = 0;
        // await require('extract-zip')(src, { dir: dst });
        const AdmZip = require("adm-zip");
        // reading archives
        var zip = new AdmZip(src);
        var zipEntries = zip.getEntries(); // an array of ZipEntry records

        zipEntries.forEach((entry, index, entries) => {
            console.log(entry.toString()); // outputs zip entries information
            const fileName = il.decode(entry.rawEntryName, encoding || "cp936"); // cp866
            const compressedData = entry.getCompressedData();
            const uncompressedData = entry.getData();
            display_tool.progress(index, entries.length, {
                desc: `Unzipping ${fileName} ${format_bytes(compressedData.length)} >>> ${format_bytes(uncompressedData.length)}`,
                depth: 0,
                color: "cyan",
                align: true,
            });
            if (entry.isDirectory) {
                fs.mkdirSync(path.join(dst, fileName));
            } else {
                fs.writeFileSync(path.join(dst, fileName), entry.getData());
            }
            display_tool.progress(index + 1, entries.length, {
                desc: `Unzipping ${fileName} ${format_bytes(compressedData.length)} >>> ${format_bytes(uncompressedData.length)}`,
                depth: 0,
                color: "cyan",
                align: true,
            });
        });
    }
}

module.exports = {
    UnzipCommand,
};
